package com.fary.chapter01_aqs.ext_countDownLatch;

import com.fary.chapter01_aqs.ext_aqs.FaryAbstractQueuedSynchronizer;

/**
 * @author Fary
 * @version 1.0
 * @description: FaryCountDownLatch
 * @date 2021/8/23 13:29
 */
public class FaryCountDownLatch {

    private final FarySync sync;

    public FaryCountDownLatch(int count) {
        if (count < 0) throw new IllegalArgumentException("count < 0");
        this.sync = new FarySync(count);
    }

    public void await() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }

    public void countDown() {
        sync.releaseShared(1);
    }

    public long getCount() {
        return sync.getCount();
    }

    private static final class FarySync extends FaryAbstractQueuedSynchronizer {
        private static final long serialVersionUID = 4982264981922014374L;

        FarySync(int count) {
            setState(count);
        }

        int getCount() {
            return getState();
        }

        protected int tryAcquireShared(int acquires) {
            return (getState() == 0) ? 1 : -1;
        }

        protected boolean tryReleaseShared(int releases) {
            // Decrement count; signal when transition to zero
            for (;;) {
                int c = getState();
                if (c == 0)
                    return false;
                int nextc = c-1;
                if (compareAndSetState(c, nextc))
                    return nextc == 0;
            }
        }
    }
}
